import java.util.TimerTask;
import java.util.concurrent.PriorityBlockingQueue;
//实现一个任务类
class MyTask implements Comparable<MyTask>{
    //runnable线程
    public Runnable runnable;
    //用绝对时间戳+delay作为任务执行的实际时间
    public long time;
    //构造方法
    public MyTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int) (this.time - o.time);
    }
}


//实现MyTimer
class MyTimer {
    //核心是一个数据结构是一个优先级的阻塞队列
    private PriorityBlockingQueue<MyTask> priorityBlockingQueue = new PriorityBlockingQueue<>();
    //锁对象
     private Object locker = new Object();
    //安排方法
    public void schedule(Runnable runnable,long delay) {
        MyTask myTask = new MyTask(runnable,delay);
        synchronized (locker) {
            priorityBlockingQueue.put(myTask);
            locker.notify();
        }
    }
    public MyTimer() {
        Thread thread = new Thread(() -> {
            while (true) {
                synchronized (locker) {
                    try {
                        MyTask myTask = priorityBlockingQueue.take();
                        long curTime = System.currentTimeMillis();
                        if(myTask.time <= curTime) {
                            myTask.runnable.run();
                        }else {
                            priorityBlockingQueue.put(myTask);
                            locker.wait(myTask.time - curTime);
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }
}




public class ThreadDemo17 {
    public static void main(String[] args) {

        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello1");
            }
        },1000);
        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello2");
            }
        },2000);
        myTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                System.out.println("hello3");
            }
        },3000);

    }
}
